/*
#include <rtthread.h>
#include <rtdevice.h>
#include <board.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <onenet.h>
#include <wlan_mgnt.h>
#include <wlan_cfg.h>
#include <rtconfig.h>

#define DBG_ENABLE
#define DBG_COLOR
#define DBG_SECTION_NAME    "onenet.sample"

#define WIFI_SSID     "LZXS"
#define WIFI_PASSWORD "15944776783"

#if ONENET_DEBUG
#define DBG_LEVEL           DBG_LOG
#else
#define DBG_LEVEL           DBG_INFO
#endif  ONENET_DEBUG

#include <rtdbg.h>

#define PIN_LED_B              GET_PIN(F, 11)      // PF11 :  LED_B        --> LED
#define PIN_LED_R              GET_PIN(F, 12)      // PF12 :  LED_R        --> LED

#ifdef FINSH_USING_MSH
#include <finsh.h>

#include "aht10.h"
#include "ap3216c.h"

static struct rt_semaphore net_ready;
static rt_bool_t wifi_connected = RT_FALSE;
static rt_bool_t onenet_initialized = RT_FALSE;

static void auto_start_onenet(void);
// 网络就绪事件处理函数
static void wlan_ready_handler(int event, struct rt_wlan_buff *buff, void *parameter)
{
    wifi_connected = RT_TRUE;
    rt_sem_release(&net_ready);
    LOG_I("Network is ready!");
}

// WiFi状态变化处理函数
static void wifi_status_handler(int event, struct rt_wlan_buff *buff, void *parameter)
{
    switch (event)
    {
    case RT_WLAN_EVT_STA_CONNECTED:
        LOG_I("WiFi connected to AP");
        wifi_connected = RT_TRUE;

        // 如果OneNET尚未初始化，尝试初始化
        if (!onenet_initialized)
        {
            rt_thread_mdelay(2000); // 等待网络稳定
            auto_start_onenet();
        }
        break;

    case RT_WLAN_EVT_STA_DISCONNECTED:
        LOG_W("WiFi disconnected");
        wifi_connected = RT_FALSE;
        break;

    case RT_WLAN_EVT_STA_CONNECTED_FAIL:
        LOG_E("WiFi connection failed");
        break;
    }
}

// WiFi自动连接函数
static int wifi_auto_connect(void)
{
    rt_err_t result = RT_EOK;

    // 初始化网络就绪信号量
    rt_sem_init(&net_ready, "net_ready", 0, RT_IPC_FLAG_FIFO);

    // 注册WiFi事件处理函数
    rt_wlan_register_event_handler(RT_WLAN_EVT_READY, wlan_ready_handler, RT_NULL);
    rt_wlan_register_event_handler(RT_WLAN_EVT_STA_CONNECTED, wifi_status_handler, RT_NULL);
    rt_wlan_register_event_handler(RT_WLAN_EVT_STA_CONNECTED_FAIL, wifi_status_handler, RT_NULL);
    rt_wlan_register_event_handler(RT_WLAN_EVT_STA_DISCONNECTED, wifi_status_handler, RT_NULL);

    // 设置工作模式为station模式
    rt_wlan_set_mode(RT_WLAN_DEVICE_STA_NAME, RT_WLAN_STATION);

    // 配置自动重连
    rt_wlan_config_autoreconnect(RT_TRUE);

    // 连接热点
    LOG_I("Connecting to WiFi: %s", WIFI_SSID);
    result = rt_wlan_connect(WIFI_SSID, WIFI_PASSWORD);

    if (result == RT_EOK)
    {
        // 等待网络就绪（30秒超时）
        if (rt_sem_take(&net_ready, rt_tick_from_millisecond(30000)) == RT_EOK)
        {
            LOG_I("WiFi connected successfully!");
            return RT_EOK;
        }
        else
        {
            LOG_E("WiFi connection timeout!");
            return -RT_ETIMEOUT;
        }
    }
    else
    {
        LOG_E("WiFi connect failed! Error: %d", result);
        return result;
    }
}

// OneNET初始化函数
static int onenet_auto_init(void)
{
    if (onenet_initialized)
    {
        LOG_W("OneNET already initialized");
        return 0;
    }

    LOG_I("Initializing OneNET MQTT...");
    int ret = onenet_mqtt_init();

    if (ret < 0)
    {
        LOG_E("OneNET MQTT initialize failed! Error: %d", ret);
        return -1;
    }

    LOG_I("OneNET MQTT initialize success!");
    onenet_initialized = RT_TRUE;
    return 0;
}

static void onenet_upload_entry(void *parameter)
{
    LOG_I("OneNET upload thread started");

    // 等待WiFi连接就绪
    while (!wifi_connected)
    {
        LOG_I("Waiting for WiFi connection...");
        rt_thread_mdelay(1000);
    }

    LOG_I("WiFi connected, initializing sensors...");

    float humidity, temperature, brightness;
    char temp_str[16];
    char humi_str[16];
    char bright_str[16];

    aht10_device_t dev1 = RT_NULL;
    ap3216c_device_t dev2 = RT_NULL;

     总线名称
    const char *i2c_bus_name1 = "i2c2";
    const char *i2c_bus_name2 = "i2c3";

     初始化 ap3216c
    dev2 = ap3216c_init(i2c_bus_name1);
    if (dev2 == RT_NULL)
    {
        LOG_E("ap3216c initializes failure.");
    }
    else
    {
        LOG_I("ap3216c initialized successfully");
    }

     等待传感器正常工作
    rt_thread_mdelay(2000);

     初始化 aht10
    dev1 = aht10_init(i2c_bus_name2);
    if (dev1 == RT_NULL)
    {
        LOG_E("aht10 initializes failure");
    }
    else
    {
        LOG_I("aht10 initialized successfully");
    }

    if (dev1 == RT_NULL || dev2 == RT_NULL)
    {
        LOG_E("Sensor initialization failed, stopping upload thread");
        return;
    }

    while (1)
    {
        // 检查网络连接
        if (!wifi_connected)
        {
            LOG_W("WiFi disconnected, waiting for reconnection...");
            while (!wifi_connected)
            {
                rt_thread_mdelay(1000);
            }
            LOG_I("WiFi reconnected, resuming upload");
        }

        // 读取传感器数据
        temperature = aht10_read_temperature(dev1);
        humidity = aht10_read_humidity(dev1);
        brightness = ap3216c_read_ambient_light(dev2);

        LOG_D("Raw sensor readings - Temp: %.2f, Humi: %.2f, Bright: %.2f",
              temperature, humidity, brightness);

        // 四舍五入到两位小数
        temperature = (float)(((int)(temperature * 100 + 0.5)) / 100.0);
        humidity = (float)(((int)(humidity * 100 + 0.5)) / 100.0);
        brightness = (float)(((int)(brightness * 100 + 0.5)) / 100.0);

        // 手动分离整数和小数部分
        int temp_int = (int)temperature;
        int temp_dec = (int)((temperature - temp_int) * 100);

        int humi_int = (int)humidity;
        int humi_dec = (int)((humidity - humi_int) * 100);

        int bright_int = (int)brightness;
        int bright_dec = (int)((brightness - bright_int) * 100);

        // 构造字符串
        rt_snprintf(temp_str, sizeof(temp_str), "%d.%02d", temp_int, temp_dec);
        rt_snprintf(humi_str, sizeof(humi_str), "%d.%02d", humi_int, humi_dec);
        rt_snprintf(bright_str, sizeof(bright_str), "%d.%02d", bright_int, bright_dec);

        LOG_D("Formatted data - Temp: %s, Humi: %s, Bright: %s", temp_str, humi_str, bright_str);

        // 使用字符串上传
        LOG_I("Uploading temperature: %s", temp_str);
        if (onenet_mqtt_upload_string("temperature", temp_str) < 0)
        {
            LOG_E("Temperature upload failed!");
        }
        else
        {
            LOG_D("Temperature uploaded successfully");
        }

        rt_thread_mdelay(500);

        LOG_I("Uploading humidity: %s", humi_str);
        if (onenet_mqtt_upload_string("humidity", humi_str) < 0)
        {
            LOG_E("Humidity upload failed!");
        }
        else
        {
            LOG_D("Humidity uploaded successfully");
        }

        rt_thread_mdelay(500);

        LOG_I("Uploading brightness: %s", bright_str);
        if (onenet_mqtt_upload_string("brightness", bright_str) < 0)
        {
            LOG_E("Brightness upload failed!");
        }
        else
        {
            LOG_D("Brightness uploaded successfully");
        }

        LOG_I("Upload cycle completed, waiting for next cycle...");
        rt_thread_delay(rt_tick_from_millisecond(5 * 1000));
    }
}

// 自动启动OneNET上传任务
static void auto_start_onenet(void)
{
    LOG_I("Starting OneNET auto upload...");

    // 初始化OneNET
    if (onenet_auto_init() != 0)
    {
        LOG_E("OneNET initialization failed, retrying in 5 seconds...");
        rt_thread_mdelay(5000);

        // 重试初始化
        if (onenet_auto_init() != 0) {
            LOG_E("OneNET initialization failed after retry, giving up");
            return;
        }
    }

    // 创建并启动上传线程
    rt_thread_t tid = rt_thread_create("onenet_auto",
                           onenet_upload_entry,
                           RT_NULL,
                           3 * 1024,  // 增加栈大小
                           RT_THREAD_PRIORITY_MAX / 3 - 1,
                           5);
    if (tid)
    {
        rt_thread_startup(tid);
        LOG_I("OneNET auto upload started!");
    }
    else
    {
        LOG_E("Failed to create OneNET upload thread!");
    }
}

// 自动连接初始化
static int auto_connect_init(void)
{
    LOG_I("Starting auto connection sequence...");

    // 重置状态标志
    wifi_connected = RT_FALSE;
    onenet_initialized = RT_FALSE;

    // 初始化WiFi连接
    wifi_auto_connect();

    return 0;
}
INIT_APP_EXPORT(auto_connect_init);

 以下为原有的命令导出函数，保留以便调试使用

int onenet_upload_cycle(void)
{
    auto_start_onenet();
    return 0;
}
MSH_CMD_EXPORT(onenet_upload_cycle, send data to OneNET cloud cycle);

int onenet_publish_digit(int argc, char **argv)
{
    if (argc != 3)
    {
        LOG_E("onenet_publish [datastream_id]  [value]  - mqtt pulish digit data to OneNET.");
        return -1;
    }

    int ret = onenet_mqtt_upload_digit(argv[1], atoi(argv[2]));
    if (ret < 0)
    {
        LOG_E("Upload digit data failed! Error: %d", ret);
    }
    else
    {
        LOG_I("Digit data uploaded successfully");
    }

    return ret;
}
MSH_CMD_EXPORT_ALIAS(onenet_publish_digit, onenet_mqtt_publish_digit, send digit data to onenet cloud);

int onenet_publish_string(int argc, char **argv)
{
    if (argc != 3)
    {
        LOG_E("onenet_publish [datastream_id]  [string]  - mqtt pulish string data to OneNET.");
        return -1;
    }

    int ret = onenet_mqtt_upload_string(argv[1], argv[2]);
    if (ret < 0)
    {
        LOG_E("Upload string data failed! Error: %d", ret);
    }
    else
    {
        LOG_I("String data uploaded successfully");
    }

    return ret;
}
MSH_CMD_EXPORT_ALIAS(onenet_publish_string, onenet_mqtt_publish_string, send string data to onenet cloud);

 onenet mqtt command response callback function
static void onenet_cmd_rsp_cb(uint8_t *recv_data, size_t recv_size, uint8_t **resp_data, size_t *resp_size)
{
    char res_buf[] = { "cmd is received!\n" };

    LOG_D("Received command: %x:%x", recv_data[0], recv_data[1]);

    if(recv_data[0] == 0x00)
    {
        rt_pin_write(PIN_LED_B, recv_data[1] > 0 ? PIN_HIGH : PIN_LOW);
        LOG_I("Blue light %s", recv_data[1] > 0 ? "ON" : "OFF");
    }
    else if(recv_data[0] == 0x01)
    {
        rt_pin_write(PIN_LED_R, recv_data[1] > 0 ? PIN_HIGH : PIN_LOW);
        LOG_I("Red light %s", recv_data[1] > 0 ? "ON" : "OFF");
    }

     Allocate memory for response data
    *resp_data = (uint8_t *) ONENET_MALLOC(strlen(res_buf));
    if (*resp_data == RT_NULL) {
        LOG_E("Failed to allocate memory for response");
        *resp_size = 0;
        return;
    }

    rt_strncpy((char *)*resp_data, res_buf, strlen(res_buf));
    *resp_size = strlen(res_buf);
}

 set the onenet mqtt command response callback function
int onenet_set_cmd_rsp(int argc, char **argv)
{
    rt_pin_mode(PIN_LED_B, PIN_MODE_OUTPUT);
    rt_pin_mode(PIN_LED_R, PIN_MODE_OUTPUT);
    onenet_set_cmd_rsp_cb(onenet_cmd_rsp_cb);
    LOG_I("OneNET command response callback set");
    return 0;
}
MSH_CMD_EXPORT(onenet_set_cmd_rsp, set cmd response function);

#endif  FINSH_USING_MSH

*/
